package com.abso.mp3tunes.locker.ui.actions;

import java.io.IOException;
import java.io.PrintWriter;

import org.eclipse.core.runtime.IProgressMonitor;

import com.abso.mp3tunes.locker.core.data.Track;
import com.abso.mp3tunes.locker.ui.LockerImages;
import com.abso.mp3tunes.locker.ui.viewers.LockerViewer;

/**
 * Action able to export a M3U playlist.
 */
public class ExportM3UPlaylistAction extends AbstractExportPlaylistAction {

	/**
	 * Constructs a new action.
	 * 
	 * @param lockerViewer
	 *            the Locker tree viewer.
	 */
	public ExportM3UPlaylistAction(LockerViewer lockerViewer) {
		super("M3U", LockerImages.getDescriptor(LockerImages.M3U), lockerViewer);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.abso.mp3tunes.locker.ui.actions.AbstractExportPlaylistAction#getFileFilterExtensions()
	 */
	protected String[] getFileFilterExtensions() {
		return new String[] { "*.m3u" };
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.abso.mp3tunes.locker.ui.actions.AbstractExportPlaylistAction#getFileEncoding()
	 */
	protected String getFileEncoding() {
		return "ISO-8859-1";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.abso.mp3tunes.locker.ui.actions.AbstractExportPlaylistAction#exportTracks(com.abso.mp3tunes.locker.core.data.Track[],
	 *      java.io.PrintWriter, org.eclipse.core.runtime.IProgressMonitor)
	 */
	protected void exportTracks(Track[] tracks, PrintWriter writer,
			IProgressMonitor monitor) throws IOException {
		writer.println("#EXTM3U");
		for (int i = 0; i < tracks.length; i++) {
			if (monitor.isCanceled()) {
				break;
			}
			writer.print("#EXTINF:");
			writer.print((int) (tracks[i].getLength() / 1000));
			writer.print(',');
			writer.print(tracks[i].getArtistName());
			writer.print(" - ");
			writer.print(tracks[i].getAlbumTitle());
			writer.print(" - ");
			writer.println(tracks[i].getTitle());
			writer.println(tracks[i].getPlayURL());
			monitor.worked(1);
		}
	}

	/* (non-Javadoc)
	 * @see com.abso.mp3tunes.locker.ui.actions.AbstractExportPlaylistAction#getPlaylistPath(java.lang.String)
	 */
	protected String getPlaylistPath(String filePath) {
		String playlistPath = filePath;
		if (!playlistPath.toLowerCase().endsWith(".m3u")) {
			return playlistPath + ".m3u";
		} else {
			return playlistPath;
		}
	}

}
